package main

import (
	"flag"
	"gin-gateway/core"
	"gin-gateway/router"
	"log"
	"os"
	"os/signal"
	"syscall"

	"gin-gateway/core/init"
	"gin-gateway/core/dao"
	"github.com/gin-gonic/gin"
)

//endpoint dashboard后台管理  server代理服务器
//config ./conf/prod/ 对应配置文件夹
var (
	endpoint   = flag.String("endpoint", "dashboard", "input endpoint dashboard or server")
	configPath = flag.String("config", "./conf/dev/", "input config file like ./conf/dev/")
)

func main() {
	flag.Parse()
	if *endpoint == "" || *configPath == "" {
		flag.Usage()
		os.Exit(1)
	}

	err := Init.InitModule(*configPath, []string{"base", "mysql", "redis", "etcd"})
	if err != nil {
		log.Fatalln(err)
	}
	defer Init.Destroy()

	if *endpoint == "dashboard" {
		router.DashboardHttpServerRun()

		quit := make(chan os.Signal, 1)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit

		router.DashboardHttpServerStop()
	} else {
		gin.SetMode(Init.GetStringConf("proxy.base.debug_mode"))
		err = dao.ServiceManagerHandler.LoadOnce()
		if err != nil {
			log.Fatalln("dao.ServiceManagerHandler.LoadOnce() err: ", err)
		}
		err = dao.AppManagerHandler.LoadOnce()
		if err != nil {
			log.Fatalln("dao.AppManagerHandler.LoadOnce() err:", err)
		}
		core.InitCircuitConfig()

		go func() {
			router.HttpProxyServerRun()
		}()
		go func() {
			router.HttpsProxyServerRun()
		}()
		go func() {
			router.TcpProxyServerRun()
		}()
		go func() {
			router.GrpcProxyServerRun()
		}()

		quit := make(chan os.Signal, 1)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit

		router.HttpProxyServerStop()
		router.HttpsProxyServerStop()
		router.GrpcProxyServerStop()
		router.TcpProxyServerStop()
	}
}
